import moment from "moment";
import requestFunc from "./request";
import config from "./config";
import { Alert } from "react-native";
export function getBgColorByType(type) {
  switch (type) {
    case "大便":
      return "#ffd700";
    case "小便":
      return "#fff8dc";
    case "纸尿裤":
      return "#00ff00";
    case "母乳":
      return "#D2B48C";
    case "奶粉":
      return "#FFFF00";
    case "辅食":
      return "#FFA500";
    case "身高":
      return "#FFA07A";
    case "体重":
      return "#FF7F50";
  }
  return "red";
}
export function getTColorByType(type) {
  return hexToReverse(getBgColorByType(type));
}
export function hexToReverse(hex) {
  if (hex.indexOf("#") === 0) {
    hex = hex.slice(1);
  }
  // convert 3-digit hex to 6-digits.
  if (hex.length === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
  if (hex.length !== 6) {
    throw new Error("Invalid HEX color.");
  }
  // invert color components
  var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
    g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
    b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
  // pad each with zeros and return
  return "#" + padZero(r) + padZero(g) + padZero(b);
}
function padZero(str, len) {
  len = len || 2;
  var zeros = new Array(len).join("0");
  return (zeros + str).slice(-len);
}

export function request(url, params, success, fail) {
  return requestFunc(url, params, success, fail);
}

export function vcodeImage(cid) {
  return config.website + "/v1/user/vcodeImage?cid=" + cid;
}

export function getUserName(userInfo) {
  if (!userInfo) {
    userInfo = getUserInfo();
  }
  if (!userInfo.Phone && !userInfo.Email) {
    return "试用账号";
  }
  if (userInfo.Name) {
    return userInfo.Name;
  }
  return userInfo.Phone;
}

export function getUserInfo() {
  if (!global.userInfo) {
    global.userInfo = {};
  }
  return global.userInfo;
}

export function getRandomFileName() {
  var text = "";
  var possible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 8; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  return moment().format("YYYYMMDDHHmmss") + text;
}

export function getFileExtension(filePath) {
  if (!filePath) {
    return "";
  }
  return filePath.split(".").pop();
}

export function getNameByUrl(url) {
  if (!url) {
    return "";
  }
  if (url.includes("?")) {
    url = url.split("?")[0];
  }
  return url.split("/").pop();
}

export function isTryOut(msg, navigation) {
  let isTryOut = !getUserInfo().Phone;
  if (isTryOut && msg) {
    Alert.alert("试用账号无法" + msg, "请先注册", [
      { text: "确定", onPress: _ => navigation.navigate("Register") },
      { text: "取消" }
    ]);
  }
  return isTryOut;
}
